package com.seecen.HJM.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.HJM.constant.MessageConstant;
import com.seecen.HJM.mapper.PlaylistMapper;
import com.seecen.HJM.mapper.SongMapper;
import com.seecen.HJM.model.dto.PlayListBindingDTO;
import com.seecen.HJM.model.dto.PlaylistGetSongDto;
import com.seecen.HJM.model.entity.Playlist;
import com.seecen.HJM.model.entity.PlaylistBinding;
import com.seecen.HJM.model.entity.Song;
import com.seecen.HJM.result.DataVo;
import com.seecen.HJM.result.PageResult;
import com.seecen.HJM.service.PlaylistBindingService;
import com.seecen.HJM.mapper.PlaylistBindingMapper;
import com.seecen.HJM.service.PlaylistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author jiachen
* @description 针对表【tb_playlist_binding】的数据库操作Service实现
* @createDate 2025-09-28 17:40:33
 *
*/
@Service
public class PlaylistBindingServiceImpl extends ServiceImpl<PlaylistBindingMapper, PlaylistBinding>
    implements PlaylistBindingService{
    @Autowired
    PlaylistBindingMapper playlistBindingMapper;
    @Autowired
    PlaylistMapper playlistMapper;
    @Autowired
    SongMapper songMapper;
    @Override

    public DataVo addSongsToPlaylist(PlayListBindingDTO dto) {
        Long playlistId = dto.getPlaylistId();
        List<Long> songIds = dto.getSongIds();

        // 1. 基础校验：歌单
        Playlist playlist = playlistMapper.selectById(playlistId);
        if (playlist == null) {
            return DataVo.error(MessageConstant.PLAYLIST + MessageConstant.NOT_FOUND);
        }
        //歌曲是否存在
        List<Long> existSongIds = songMapper.selectBatchIds(songIds).stream()
                .map(Song::getId)
                .collect(Collectors.toList());
        if (existSongIds.isEmpty()) {
            return DataVo.error(MessageConstant.SONG + MessageConstant.NOT_FOUND);
        }

        // 2. 联合主键校验：查询歌单中已存在的歌曲（避免重复添加）
        List<Long> alreadyInIds = playlistBindingMapper.checkBatchSongsInPlaylist(playlistId, existSongIds);
        if (!alreadyInIds.isEmpty()) {
            return DataVo.error("歌曲ID：" + alreadyInIds + " 已在歌单中（联合主键冲突），无需重复添加");
        }

        // 3. 构建联合主键关联对象列表
        List<PlaylistBinding> bindings = existSongIds.stream()
                .map(songId -> {
                    PlaylistBinding binding = new PlaylistBinding();
                    binding.setPlaylistId(playlistId);
                    binding.setSongId(songId);
                    return binding;
                })
                .collect(Collectors.toList());

        // 4. 批量插入（用自定义的 batchInsertBindings，适配联合主键）
        Integer insertCount = playlistBindingMapper.insertBindings(bindings);
        if (insertCount == null || insertCount == 0) {
            return DataVo.error(MessageConstant.ADD_SONG_TO_PLAYLIST + MessageConstant.FAILED);
        }

        return DataVo.success("成功添加 " + insertCount + " 首歌曲到歌单");
    }

    @Override
    public DataVo removeSongsFromPlaylist(PlayListBindingDTO dto) {
        Long playlistId = dto.getPlaylistId();
        List<Long> songIds = dto.getSongIds();

        // 1. 基础校验：歌单是否存在（同之前逻辑，此处省略）
        Playlist playlist = playlistMapper.selectById(playlistId);
        if (playlist == null) {
            return DataVo.error(MessageConstant.PLAYLIST + MessageConstant.NOT_FOUND);
        }

        // 2. 联合主键校验：查询歌单中实际存在的歌曲（避免删除不存在的关联）
        List<Long> existInIds = playlistBindingMapper.checkBatchSongsInPlaylist(playlistId, songIds);
        if (existInIds.isEmpty()) {
            return DataVo.error("所选歌曲均不在歌单中（无匹配的联合主键），无需删除");
        }

        // 3. 批量删除（用自定义的 batchDeleteBindings，基于联合主键）
        Integer deleteCount = playlistBindingMapper.deleteBindings(playlistId, existInIds);
        if (deleteCount == null || deleteCount == 0) {
            return DataVo.error(MessageConstant.REMOVE_SONG_FROM_PLAYLIST + MessageConstant.FAILED);
        }

        return DataVo.success("成功删除歌单中的 " + deleteCount + " 首歌曲");
    }

    @Override
    public DataVo<PageResult<Song>> getSongsByPlaylistId(PlaylistGetSongDto playlistGetSongDto) {
        // 1. 基础校验：歌单ID不能为空
        if (playlistGetSongDto.getId() == null || playlistGetSongDto.getId() <= 0) {
            return DataVo.error("歌单ID无效，请传入正确的歌单ID");
        }

        // 2. 校验歌单是否存在（避免查询不存在的歌单）
        Playlist playlist = playlistMapper.selectById(playlistGetSongDto.getId());
        if (playlist == null) {
            return DataVo.error(MessageConstant.PLAYLIST + MessageConstant.NOT_FOUND);
        }

        // 3. 分页查询歌单与歌曲的关联关系（修正QueryWrapper拼写，修复Mapper命名）
        Page<PlaylistBinding> page = new Page<>(
                playlistGetSongDto.getPageNum(),  // 当前页码（MyBatis-Plus分页默认页码从1开始，无需转换）
                playlistGetSongDto.getPageSize()  // 每页条数
        );
        // 正确使用QueryWrapper，添加歌单ID条件
        QueryWrapper<PlaylistBinding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("playlist_id", playlistGetSongDto.getId());

        // 执行分页查询（修正Mapper重复命名问题：playlistBindingMapper）
        IPage<PlaylistBinding> playlistBindingsPage = playlistBindingMapper.selectPage(page, queryWrapper);

        // 4. 从关联关系中提取歌曲ID列表（Stream流处理，避免空指针）
        List<Long> songIds = playlistBindingsPage.getRecords().stream()
                .filter(binding -> binding.getSongId() != null)  // 过滤无效的歌曲ID
                .map(PlaylistBinding::getSongId)
                .collect(Collectors.toList());

        // 5. 批量查询歌曲信息（减少数据库交互，提升性能）
        List<Song> songList = Collections.emptyList();
        if (!songIds.isEmpty()) {
            songList = songMapper.selectBatchIds(songIds);
        }

        return DataVo.success(new PageResult<>(playlistBindingsPage.getTotal(),songList));
    }
}




